import React, { useEffect, useState } from 'react';
import { Table, Button, Space, Tag, message, Popconfirm } from 'antd';
import { EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { fetchFlights, deleteFlight, searchFlights } from '../../store/slices/flightSlice';
import FlightSearch from './FlightSearch';

const FlightList = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { flights, loading, pagination } = useSelector((state) => state.flights);

  useEffect(() => {
    dispatch(fetchFlights());
  }, [dispatch]);

  const handleDelete = async (id) => {
    try {
      await dispatch(deleteFlight(id)).unwrap();
      message.success('航班删除成功');
    } catch (error) {
      message.error('删除失败: ' + error.message);
    }
  };

  const handleEdit = (id) => {
    navigate(`/flights/edit/${id}`);
  };



  const columns = [
    {
      title: '航班号',
      dataIndex: 'flight_number',
      key: 'flight_number',
      fixed: 'left',
      width: 100,
    },
    {
      title: '出发城市',
      dataIndex: 'departure_city',
      key: 'departure_city',
      width: 100,
    },
    {
      title: '到达城市',
      dataIndex: 'arrival_city',
      key: 'arrival_city',
      width: 100,
    },
    {
      title: '出发机场',
      dataIndex: 'departure_airport',
      key: 'departure_airport',
      width: 120,
    },
    {
      title: '到达机场',
      dataIndex: 'arrival_airport',
      key: 'arrival_airport',
      width: 120,
    },
    {
      title: '出发时间',
      dataIndex: 'departure_time',
      key: 'departure_time',
      width: 160,
      render: (text) => new Date(text).toLocaleString('zh-CN'),
    },
    {
      title: '到达时间',
      dataIndex: 'arrival_time',
      key: 'arrival_time',
      width: 160,
      render: (text) => new Date(text).toLocaleString('zh-CN'),
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      width: 80,
      render: (text) => `¥${text}`,
    },
    {
      title: '座位',
      key: 'seats',
      width: 100,
      render: (_, record) => (
        <span>
          {record.available_seats}/{record.total_seats}
        </span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status) => {
        const colorMap = {
          scheduled: 'blue',
          boarding: 'green',
          departed: 'orange',
          arrived: 'purple',
          cancelled: 'red',
        };
        const textMap = {
          scheduled: '已安排',
          boarding: '登机中',
          departed: '已起飞',
          arrived: '已到达',
          cancelled: '已取消',
        };
        return <Tag color={colorMap[status]}>{textMap[status]}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 120,
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record.id)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个航班吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];



  return (
    <div>
      <FlightSearch />
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          size="large"
          onClick={() => navigate('/flights/create')}
        >
          添加航班
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={flights}
        rowKey="id"
        loading={loading}
        scroll={{ x: 1300 }}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
        }}
        onChange={(pagination) => {
          dispatch(fetchFlights({
            page: pagination.current,
            page_size: pagination.pageSize,
          }));
        }}
      />
    </div>
  );
};

export default FlightList;